package demo;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.Scanner;

public class FileMatchDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查找的目录：");
        String rootPath = sc.nextLine();
        System.out.println("请输入要查找的内容字符串：");
        String key = sc.nextLine();
        File rootFile = new File(rootPath);
        if (!rootFile.exists() || !rootFile.isDirectory()) {
            return;
        }
        searchDir(rootFile, key);
    }

    private static void searchDir(File rootFile, String key) {
        File[] files = rootFile.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                searchDir(f, key);
            } else {
                if (matchKey(f, key)) {
                    System.out.println(f.getPath());
                }
            }
        }
    }

    private static boolean matchKey(File f, String key) {
        StringBuilder builder = new StringBuilder();
        try (Reader reader = new FileReader(f)) {
            char[] buf = new char[1024];
            while (true) {
                int len = reader.read(buf);
                if (len == -1) {
                    break;
                }
                builder.append(buf, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString().contains(key);
    }

}
